package com.shopx.base.handler;

import com.shopx.base.dto.Result;
import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.exception.OriginException;
import com.shopx.base.exception.ShopxException;
import com.shopx.base.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
  @ResponseStatus(HttpStatus.OK)
  @ExceptionHandler(Exception.class)
  protected Result handlerException(Exception e) {
    log.error("全局异常捕获：{}",e);
    String statusCode = "";
    String statusDesc = "";
    if (e instanceof ShopxException) {
      //业务异常
      statusCode = ((ShopxException) e).getStatusCode();
      statusDesc = ResultCodeEnum.getDesc(statusCode);
      return ResultUtil.fail(statusCode, statusDesc);
    } else if (e instanceof OriginException) {
      //业务自定义描述异常
      statusCode = ((OriginException) e).getStatusCode()==null?"99999":((OriginException) e).getStatusCode();
      statusDesc = ((OriginException) e).getStatusDesc() == null ? "对不起，系统开小差了" : ((OriginException) e).getStatusDesc();
      return ResultUtil.fail(statusCode, statusDesc);
    }else if(e instanceof BindException){
      //参数校验异常
      if (((BindException) e).getBindingResult().getErrorCount() > 0) {
        String message = ((BindException) e).getBindingResult().getAllErrors().get(0).getDefaultMessage();
        if (message.split("\\|").length <= 1) {
          return ResultUtil.fail("99999", message);
        }
        String code = message.split("\\|")[0];
        String codeMessage = message.split("\\|")[1];
        return ResultUtil.fail(code, codeMessage);
      }
      return ResultUtil.fail(ResultCodeEnum.INTERNAL_SERVER_ERROR);
    }else if(e instanceof MethodArgumentNotValidException){
      //参数校验异常
      String message = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().get(0).getDefaultMessage();
      if (message.split("\\|").length <= 1) {
        return ResultUtil.fail("99999", message);
      }
      String code = message.split("\\|")[0];
      String codeMessage = message.split("\\|")[1];
      return ResultUtil.fail(code, codeMessage);
    }else {
      //运行未捕获异常
      String exMessage = e.getMessage();
      if(exMessage==null){
        return ResultUtil.fail(ResultCodeEnum.INTERNAL_SERVER_ERROR);
      }
      if (exMessage.indexOf("Duplicate") > 0) {
        //数据重复异常
        return ResultUtil.fail(ResultCodeEnum.DATA_DUPLICATE_KEY);
      }
      return ResultUtil.fail(ResultCodeEnum.INTERNAL_SERVER_ERROR);
    }
  }
}
